package com.photolibrary.base.load;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.photolibrary.R;
import com.photolibrary.bean.BaseMedia;
import com.photolibrary.ui.ImgSelectorActivity;
import com.photolibrary.ui.ImgViewActivity;
import com.yanzhenjie.permission.AndPermission;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * 作者： ch
 * 时间： 2018/4/9 0009-下午 4:55
 * 描述：
 * 来源：
 */


public class PSManager {
    private static PSManager manager;
    private static PSConfig mConfig;
    private PopupWindow pop;


    /**
     * 拍照
     */
    private static final int REQUEST_CODE_CAPTURE_CAMEIA = 10000;
    /**
     * 从相册选择
     */
    private static final int REQUEST_CODE_PICK_IMAGE = 10001;
    /**
     * 相册多选
     */
    private static final int REQUEST_CODE_PICK_IMAGE_MULT = 10002;

    /**
     * 剪切
     */
    private static final int CROP_REQUEST_CODE = 4;
    private static String basePath;
    private static Uri photoUri;
    private static String crop;

    public PSManager(PSConfig mConfig) {
        this.mConfig = mConfig;
    }

    public static PSConfig getmConfig() {
        return mConfig;
    }

    public void setmConfig(PSConfig mConfig) {
        this.mConfig = mConfig;

    }

    public static PSManager of() {
        PSConfig config = new PSConfig().withMaxCount(1).withSpanCount(2);
        manager = new PSManager(config);
        return manager;
    }

    public static PSManager of(PSConfig config) {
        manager = new PSManager(config);
        return manager;
    }

    public void forPreView(Context context, ArrayList<BaseMedia> list, int postion) {
        Intent intent = new Intent();
        intent.setClass(context, ImgViewActivity.class);
        intent.putParcelableArrayListExtra(PSConfig.IMG_CONTENT, list);
        intent.putExtra(PSConfig.IMG_POSITION, postion);
        context.startActivity(intent);
        if (context instanceof Activity) {
            ((Activity) context).overridePendingTransition(R.anim.activity_zoom_open, 0);
        }
    }

    public void forPreView(Context context, ArrayList<BaseMedia> list) {
        forPreView(context, list, 0);
    }

    /**
     * 打开相册
     *
     * @param activity
     */
    public void forAlbum(Activity activity) {
        if (activity == null) {
            return;
        }

        if (getmConfig().isUseSysAlbum()) {
            getImageFromAlbum(activity);// 从相册里获取
        } else {
            activity.startActivityForResult(new Intent(activity, ImgSelectorActivity.class), REQUEST_CODE_PICK_IMAGE_MULT);
        }
    }

    /**
     * 打开相机、相册 选择框
     *
     * @param activity
     * @param parent
     */
    public void forDialog(Activity activity, View parent) {

        basePath = Environment.getExternalStorageDirectory() + "/" + getAppPackageName(activity) + "/";
        View view = LayoutInflater.from(activity).inflate(R.layout.popw_alert_select_phone, null);
        initView(activity, view);
        pop = new PopupWindow(activity);
        pop.setContentView(view);
        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        pop.setBackgroundDrawable(dw);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (pop != null && pop.isShowing()) {
                    pop.dismiss();
                }
                return false;
            }
        });
        pop.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 裁剪
     *
     * @param uri
     */
    public static void forCrop(Uri uri, Activity activity) {
        File fileDir = new File(basePath + "corp/");
        if (!fileDir.exists()) {// 目录是否存在
            fileDir.mkdirs();// 创建
        }
        crop = basePath + "corp/" + System.currentTimeMillis() + ".jpg";
        Uri imageUri = Uri.parse("file://" + crop);
        final Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("noFaceDetection", false); // 不启用人脸识别
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", false);
        intent.putExtra("return-data", false);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        activity.startActivityForResult(intent, CROP_REQUEST_CODE);
    }


    private void initView(Activity activity, View view) {
        TextView tv_photograph = view.findViewById(R.id.tv_photograph);
        TextView tv_album = view.findViewById(R.id.tv_album);
        LinearLayout ll_cancle_layout = view.findViewById(R.id.ll_cancle_layout);
        tv_photograph.setOnClickListener(new MyOnClickListener(activity));
        tv_album.setOnClickListener(new MyOnClickListener(activity));
        ll_cancle_layout.setOnClickListener(new MyOnClickListener(activity));

    }


    private class MyOnClickListener implements View.OnClickListener {

        private Activity activity;

        public MyOnClickListener(Activity activity) {
            this.activity = activity;
        }

        @Override
        public void onClick(View v) {
            int i = v.getId();
            if (i == R.id.tv_photograph) {
                if (AndPermission.hasPermission(activity, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    // 有权限，直接do anything.
                    forCamera(activity);
                } else {
                    // 申请权限。
                    AndPermission.with(activity)
                            .requestCode(100)
                            .permission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .send();
                }


                if (pop != null) {
                    pop.dismiss();
                }

                // 相册
            } else if (i == R.id.tv_album) {
                if (AndPermission.hasPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
                )) {
                    // 有权限，直接do anything.
                    forAlbum(activity);

                } else {
                    // 申请权限。
                    AndPermission.with(activity)
                            .requestCode(101)
                            .permission(Manifest.permission.READ_EXTERNAL_STORAGE,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .send();
                }
                if (pop != null) {
                    pop.dismiss();
                }

                // 取消
            } else if (i == R.id.ll_cancle_layout) {
                if (pop != null && pop.isShowing()) {
                    pop.dismiss();
                }

            } else {
            }
        }
    }

    /**
     * 从相册里选取
     */
    public void getImageFromAlbum(Activity activity) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        activity.startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }

    /**
     * 获取安卓系统照相机拍照
     */
    public void forCamera(Activity activity) {

        Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
        String state = Environment.getExternalStorageState();
        // 检查是否有存储卡
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            // 创建位置
            File fileDir = new File(basePath);
            if (!fileDir.exists()) {// 目录是否存在
                fileDir.mkdirs();
            }

            File file = new File(basePath + System.currentTimeMillis() + ".jpg");
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {

                photoUri = Uri.fromFile(file);
                // Create path for temp file
                // 相机存储的地址
            } else {
                photoUri = FileProvider.getUriForFile(activity, getAppPackageName(activity) + ".FileProvider", file);
                getImageByCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            activity.startActivityForResult(getImageByCamera, REQUEST_CODE_CAPTURE_CAMEIA);// 拍照完送去裁剪
        }
    }


    public static PSManager getInstance() {
        if (manager == null) {
            manager = PSManager.of();
        }
        return manager;
    }

    public static void getResult(int requestCode, int resultCode, Intent data, Activity activity, ResultCallBack callBack) {
        if (resultCode == -1) {
            if (requestCode == REQUEST_CODE_PICK_IMAGE) {
                //相册
                if (null != data) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        //相机
                        if (uri.getPath().startsWith("/external/") || uri.getPath().startsWith("/raw/")) {
                            String path = getFilePathFromContentUri(uri, activity.getContentResolver());
                            if (callBack != null) {
                                callBack.formSysAlbum(path);
                            }
                        } else {
                            if (callBack != null) {
                                callBack.formSysAlbum(uri.getPath());
                            }
                        }
                    }
                }

            } else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    callBack.formCamera(photoUri.getPath());
                } else {
                    String url = photoUri.getPath();
                    if (url.contains("files_root")) {
                        String base = Environment.getExternalStorageDirectory().getPath();
                        if (callBack != null) {
                            callBack.formCamera(base + url.substring(url.indexOf("files_root") + 10));
                        }
                    }
                }
            } else if (requestCode == REQUEST_CODE_PICK_IMAGE_MULT) {
                //相册多选
                ArrayList<BaseMedia> list = data.getParcelableArrayListExtra(PSConfig.IMG_CONTENT);
                callBack.formMultAlbm(list);
            } else if (requestCode == CROP_REQUEST_CODE) {
                //裁剪
                if (callBack != null) {
                    callBack.forCrop(crop);
                }

            }

        }

    }

    /**
     * Gets the corresponding path to a file from the given content:// URI
     *
     * @param selectedVideoUri The content:// URI to find the file path from
     * @param contentResolver  The content resolver to use to perform the query.
     * @return the file path as a string
     */
    public static String getFilePathFromContentUri(Uri selectedVideoUri,
                                                   ContentResolver contentResolver) {
        String filePath;
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};

        Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
//      也可用下面的方法拿到cursor
//      Cursor cursor = this.context.managedQuery(selectedVideoUri, filePathColumn, null, null, null);

        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }

    public void loadMedia(ContentResolver resolver, String bucketId, int page, IMediaCallBack<BaseMedia> callBack) {
        new ImageTask(callBack, resolver, page, bucketId).execute(0);
    }


    public interface IMediaCallBack<T> {
        void postMedia(@Nullable List<T> medias, int count);
    }

    public interface ResultCallBack {
        void formCamera(String path);

        void formSysAlbum(String path);

        void formMultAlbm(ArrayList<BaseMedia> list);

        void forCrop(String path);
    }


    /**
     * 获得应用包名
     *
     * @param context
     * @return
     */
    public static String getAppPackageName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.packageName;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

}
